package com.lier.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lier.common.constant.WareConstant;
import com.lier.gulimall.ware.entity.PurchaseDetailEntity;
import com.lier.gulimall.ware.entity.WareSkuEntity;
import com.lier.gulimall.ware.service.PurchaseDetailService;
import com.lier.gulimall.ware.service.WareSkuService;
import com.lier.gulimall.ware.vo.MergeVo;
import com.lier.gulimall.ware.vo.PurchaseDoneVo;
import com.lier.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lier.common.utils.PageUtils;
import com.lier.common.utils.Query;

import com.lier.gulimall.ware.dao.PurchaseDao;
import com.lier.gulimall.ware.entity.PurchaseEntity;
import com.lier.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


/**
 * @author 66447
 */
@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    private PurchaseDetailService purchaseDetailService;

    @Resource
    private WareSkuService wareSkuService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnReceive(Map<String, Object> params) {


        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new LambdaQueryWrapper<PurchaseEntity>()
                        .eq(PurchaseEntity::getStatus, 0)
                        .or().eq(PurchaseEntity::getStatus, 1)
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            // 没有采购单id, 生成一个新的采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);

            purchaseId = purchaseEntity.getId();
        }

        // 采购单状态为新建或者已分配才能合并
        PurchaseEntity purchaseEntity = this.getById(purchaseId);
        if(purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                || purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSINGED.getCode()){
            List<Long> items = mergeVo.getItems();
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(item -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(item);
                purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                // 设置状态为已分配
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSINGED.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(purchaseDetailEntities);

            // 修改更新时间
            LambdaUpdateWrapper<PurchaseEntity> purchaseEntityLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            purchaseEntityLambdaUpdateWrapper.set(PurchaseEntity::getUpdateTime, new Date()).eq(PurchaseEntity::getId, purchaseId);
            this.update(purchaseEntityLambdaUpdateWrapper);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void received(List<Long> ids) {
        // 确认当前采购单是新建或者已分配
        List<PurchaseEntity> purchaseEntities = ids.stream().map(this::getById)
                .filter(purchaseEntity -> purchaseEntity.getStatus() != WareConstant.PurchaseStatusEnum.CREATED.getCode()
                        || purchaseEntity.getStatus() != WareConstant.PurchaseStatusEnum.ASSINGED.getCode())
                .peek(item -> {
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    item.setUpdateTime(new Date());
                })
                .collect(Collectors.toList());
        // 改变采购单状态
        this.updateBatchById(purchaseEntities);

        // 改变采购项状态
        purchaseEntities.forEach(purchaseEntity -> {
           List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService
                   .listDetailByPurchaseId(purchaseEntity.getId());

            List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailEntities.stream().map(item -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(item.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());


            purchaseDetailService.updateBatchById(purchaseDetailEntityList);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void done(PurchaseDoneVo doneVo) {

        // 改变采购项状态
        boolean flag = true;
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for(PurchaseItemDoneVo item : items){
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (WareConstant.PurchaseStatusEnum.HASERROR.getCode() == item.getStatus()) {
                flag = false;
                purchaseDetailEntity.setStatus(item.getStatus());
            }else{
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 成功状态得采购项入库
                PurchaseDetailEntity purchaseDetail = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(purchaseDetail.getSkuId(), purchaseDetail.getWareId(), purchaseDetail.getSkuNum());

            }

            purchaseDetailEntity.setId(item.getItemId());
            updates.add(purchaseDetailEntity);
        }

        purchaseDetailService.updateBatchById(updates);


        // 改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        Long id = doneVo.getId();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode()
                : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

}
